<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/8/13/013
 * Time: 9:40
 */

namespace App\Http\Controllers\Login;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Service\User\UserService;
use Session;
use Config;

class LoginController extends Controller
{
    public function login()
    {
        return view('Login.login');
    }


    /**
     * @param Request $request
     * 登录
     */
    public function doLogin(Request $request)
    {
        $where = [];

        if(!$request->has('_token') || empty($request->input('_token')))
        {
            $ret = [
                'error_code' => '10001',
                'error_message' => '参数错误',
             ];
            return $ret;
        }

        $where['agent_account'] = $request->input('username');
        $where['password'] = $request->input('password');
        $where['validateCode'] = $request->input('validateCode');
        $where['ip'] = $request->getClientIp();

        if(!isset($where['validateCode']) || empty($where['validateCode']) )
        {
            echo "<script>confirm('错误的验证码，请从新登陆？')?location.href='/  ' : history.back() ;</script>";
            exit();
        }

        $code = Session::get('VERIFICATION');
        $where['validateCode'] = strtolower($where['validateCode']);

        //   检测验证码
        $validateCode = md5($where['validateCode'].'niumokeji888');

        if($validateCode != $code)
        {
            echo "<script>confirm('错误的验证码，请从新登陆？')?location.href='/  ' : history.back() ;</script>";
            exit();
        }



        $user = new UserService();

        $data = $user->login($where);

        if($data['error_code'] == 0)
        {
            $req = $data['data'];

            Session::put(Config::get('custom.setting.MEMBER_TOKEN'),$req['token']);
            Session::put(Config::get('custom.setting.MEMBER_INFO'),$req['username']);
            Session::put(Config::get('custom.setting.MEMBER_ROLE_ID'),$req['role_id']);

            unset($data['data']);
//            dd(Session::get(Config::get('custom.setting.MEMBER_TOKEN')));
            return redirect('/home');
        }else{
            echo "<script>confirm('账号或密码不对，请从新登陆？')?location.href='/  ' : history.back() ;</script>";
            exit();
        }
    }

    /**
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     * 退出登录
     */
    public function logout(){

        Session::forget(Config::get('custom.setting.MEMBER_TOKEN'));
        Session::forget(Config::get('custom.setting.MEMBER_INFO'));
        Session::forget(Config::get('custom.setting.MEMBER_ROLE_ID'));

        return redirect('/');
    }
}